//
//  EHThirdPartyLogicViewController.swift
//  ExtremeHealth
//
//  Created by Zhongkai Li 李忠凯 on 2018/9/10.
//  Copyright © 2018 GanDongKeJi. All rights reserved.
//

import UIKit
import UIColor_Hex_Swift

public class EHThirdPartyLoginViewController: UIViewController {
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var detailLabel: UILabel!
    @IBOutlet weak var leftLine: UIView!
    @IBOutlet weak var rightLine: UIView!
    @IBOutlet weak var middelImageView: UIImageView!
    @IBOutlet weak var leftImageView: UIImageView!
    @IBOutlet weak var rightImageView: UIImageView!
    @IBOutlet weak var loginButton: UIButton!

    public override func viewDidLoad() {
        super.viewDidLoad()
        config()
    }

    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        hideNavibar(animated: false)
    }

    public override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        showNavibar(animated: false)
    }

    @IBAction func loginOrRegister(_ sender: UIButton) {
        MainCoordinator.shared.register()
    }

    @objc private func wechatLogin() {
        guard WXApi.isWXAppSupport() else { alert(); return }
        let req = SendAuthReq()
        req.scope = "snsapi_userinfo"
        req.state = "App"
        if !WXApi.send(req) {
            debugPrint("weixin sendreq failed")
        }
    }

    private func config() {
        addGradientLayer()
        configSubViews()
        configWX()
    }

    private func configWX() {
        if WXApi.isWXAppInstalled() {
            debugPrint("weixin is ready")
        }
    }

    private func alert() {
        EHDialogPresenter()
            .setTitle("")
            .setMessage("请先安装微信")
            .setOptions([("确定", UIColor("#00C8C2"), .cancel, { _ in })])
            .present(in: self)
    }

    private func addGradientLayer() {
        let colorTop = UIColor("#00C8C2").cgColor
        let colorBottom = UIColor("#036AC3").cgColor

        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = view.bounds
        gradientLayer.colors = [colorTop, colorBottom]
        gradientLayer.locations = [0.0, 1.0]
        view.layer.insertSublayer(gradientLayer, at: 0)
    }

    private func configSubViews() {
        titleLabel.textColor = .white
        detailLabel.textColor = .white
        leftLine.backgroundColor = .white
        leftLine.alpha = 0.4
        rightLine.backgroundColor = .white
        rightLine.alpha = 0.4
        middelImageView.image = UIImage(named: "icon_weixin_login")
        leftImageView.isHidden = true
        rightImageView.isHidden = true
        loginButton.backgroundColor = UIColor("#1BBAD1")
        loginButton.layer.cornerRadius = 8
        loginButton.alpha = 0.4
        middelImageView.isUserInteractionEnabled = true
        middelImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(wechatLogin)))
    }
}
